<template>
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1024px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="auto" :class="{ 'detail-disabled': currentDisabled }">
      <el-row>
        <el-col :span="18">
          <el-form-item label="合同分类" prop="contractCategory">
            <el-select
              v-model="form.contractCategory"
              placeholder="请选择合同分类"
              :disabled="currentDisabled"
              clearable
            >
              <el-option
                v-for="dict in dict.type.contract_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value * 1"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="合同进度" prop="contractProgress">
            <el-select
              v-model="form.contractProgress"
              :disabled="
                (currentDisabled && title === '查看合同信息') ||
                (currentDisabled && disabledRules.contractProgress.indexOf(form.status) < 0)
              "
              placeholder="请选择合同进度"
              clearable
            >
              <el-option
                v-for="dict in dict.type.contract_progress"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value * 1"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="封面" prop="coverImg">
            <image-upload
              :disabled="currentDisabled"
              :limit="1"
              @input="
                (val) => {
                  form.coverImg = val
                }
              "
              :value="form.coverImg"
            />
          </el-form-item> -->
          <el-form-item label="合同名称" prop="contractName">
            <el-input :disabled="currentDisabled" v-model="form.contractName" placeholder="请输入合同名称" />
          </el-form-item>
          <el-form-item label="合同编号" prop="contractNumber">
            <el-select
              placeholder="请选择编号类型"
              style="width: 200px"
              :disabled="currentDisabled"
              v-model="form.contractNumberType"
              @change="getContractNumber"
            >
              <el-option
                v-for="dict in dict.type.contract_number"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-input
              :disabled="currentDisabled"
              style="width: 240px; margin-left: 5px"
              v-model="form.contractNumber"
              v-loading="contractNumberLoading"
              placeholder="请输入合同编号"
            />
<!--          <el-checkbox v-model="contractSplit" class="ml20" @change="handleContractSplitTag">是否拆分合同</el-checkbox>-->
          </el-form-item>

          <el-form-item label="合同负责人" prop="contractManager">
            <el-select
              placeholder="输入关键词，可获取更多合同负责人"
              :disabled="currentDisabled"
              v-model="form.contractManager"
              :loading="dingTalkListLoading"
              remote
              :remote-method="getDingTalkList"
              @clear="getDingTalkList"
              filterable
              style="width: 340px"
              clearable
            >
              <el-option
                v-for="item in dingTalkList"
                :key="`ding_${item.userId}`"
                :label="item.dingTalkUserName"
                :value="item.dingTalkUserName"
              >
                {{ `${item.dingTalkUserName}${item.phone ? `-${item.phone}` : ''}` }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="项目"
            prop="projectId"
            :rules="[
              {
                required: form.contractCategory == '3' || form.contractCategory == '1',
                message: '输入关键词，可获取更多项目',
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <TableSelect
              :value="form.project"
              :isReturnRow="true"
              :dicts="dict.type"
              :defaultProps="{ label: 'projectName', value: 'id' }"
              :column="columns"
              :request="getProjectListPop"
              placeholder="请选择项目"
              @change="projectSelect"
            >
            </TableSelect>
          </el-form-item>

          <el-form-item
            label="供应商"
            prop="supplierId"
            v-if="form.contractCategory != '1'"
            :rules="[
              {
                required: true,
                message: '请选择供应商',
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <el-select
              :disabled="currentDisabled"
              v-model="form.supplierId"
              remote
              reserve-keyword
              placeholder="输入关键词，可获取更多供应商"
              filterable
              :remote-method="getSupplierList"
              :loading="supplierLoading"
              clearable
              @clear="
                () => {
                  getSupplierList('')
                }
              "
              style="width: 100%"
            >
              <el-option
                v-for="item in supplierList"
                :key="`key_${item.id}`"
                :label="item.supplierName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="客户"
            prop="customerId"
            v-if="form.contractCategory == '1'"
            :rules="[
              {
                required: form.contractCategory == '1',
                message: '请选择客户',
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <el-select
              v-model="form.customerId"
              placeholder="输入关键词，可获取更多客户"
              :remote-method="getCustomer"
              filterable
              remote
              style="width: 480px"
              :disabled="currentDisabled || disabledCustomer"
              reserve-keyword
              clearable
              v-loading="customeLading"
              @clear="customerClear"
            >
              <el-option
                v-for="item in customeList"
                :key="`key_${item.id}`"
                :label="item.customerName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="合同金额"
            prop="contractAmount"
            :rules="[
              {
                required: form.contractProgress > 1,
                message: '请输入合同金额',
                trigger: ['change', 'blur'],
                validator: amountCheck,
              },
            ]"
          >
            <el-input-number
              controls-position="right"
              :step="100"
              :min="0"
              :disabled="checkPermi('biz:contract:information:edit:contractAmount')"
              style="width: 150px"
              :precision="2"
              v-model="form.contractAmount"
              placeholder="请输入合同金额"
            >
            </el-input-number>
            元
          </el-form-item>
          <el-form-item  label="合同负责主体" prop="contractResponsibleParty">
            <el-select
              filterable
              :disabled="currentDisabled"
              v-model="form.contractResponsibleParty"
              placeholder="请选择合同负责主体"
              clearable
            >
              <el-option
                v-for="dict in dict.type.contract_responsible_party"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="中标时间" prop="winBiddingDate">
            <el-date-picker
              clearable
              :disabled="currentDisabled"
              v-model="form.winBiddingDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择中标时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="合同签订时间" prop="contractSignDate">
            <el-date-picker
              clearable
              v-model="form.contractSignDate"
              type="date"
              :disabled="currentDisabled"
              value-format="yyyy-MM-dd"
              placeholder="请选择合同签订时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="签约主体"
            prop="signObject"
            :rules="[
              {
                required: form.contractCategory == 3 && form.contractProgress == 1 ? false : true,
                message: '请选择签约主体',
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <el-select
              filterable
              style="width: 100%"
              :disabled="currentDisabled"
              v-model="form.signObject"
              placeholder="请选择签约主体"
              clearable
            >
              <el-option
                v-for="dict in dict.type.contract_sign"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="附件列表" prop="annexDtoList">
            <file-upload
              valueType="object"
              :fileType="['pdf', 'doc', 'docx', 'xls', 'xlsx']"
              :fileSize="10"
              :disabled="currentDisabled"
              :use-original-name="true"
              @input="
                (val) => {
                  form.annexDtoList = JSON.parse(val)
                }
              "
              :limit="20"
              :value="form.annexDtoList"
            />
          </el-form-item>
          <!--          <el-form-item
            label="审批模板"
            prop="processCode"
            :rules="[
              {
                required: form.contractCategory == 3 && form.contractProgress == 1 ? false : true,
                message: '请选择审批模板',
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <el-select
              :disabled="currentDisabled"
              v-model="form.processCode"
              filterable
              remote
              reserve-keyword
              placeholder="输入关键词，可获取更多审批模板"
              :remote-method="getApprovalTemplateList"
              :loading="templateLoading"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in templateList"
                :key="`key_${item.processCode}`"
                :label="item.name"
                :value="item.processCode"
              >
              </el-option>
            </el-select>
          </el-form-item>-->
        </el-col>
      </el-row>
    </el-form>
    <el-divider></el-divider>


    <div class="title mt10" style="padding-top: 0px;" v-if="form.contractSplitTag=='1'">
      合同拆分<el-button
      @click="handleOpenModel('split')"
      :disabled="
          (currentDisabled && title === '查看合同信息') ||
          (currentDisabled && disabledRules.split.indexOf(form.status) < 0)
        "
      type="warning"
      size="mini"
    >新增</el-button
    >
    </div>
    <el-table :data="form.contractSplitList" style="width: 99%; margin: 0 auto" v-if="form.contractSplitTag=='1'">
      <el-table-column label="序号" type="index" align="center" :index="indexMethod"> </el-table-column>
      <el-table-column algin align="center" label="业务线">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_business_line" :value="scope.row.businessLineId" />
        </template>
      </el-table-column>
      <el-table-column algin align="center" label="项目类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.project_type" :value="scope.row.projectType" />
        </template>
      </el-table-column>
      <el-table-column prop="contractAmount" align="center" label="合同金额"> </el-table-column>
      <el-table-column align="center" label="操作" width="160px">
        <template slot-scope="scope">
          <el-button
            :disabled="
              (currentDisabled && title === '查看合同拆分') ||
              (currentDisabled && disabledRules.moreInfo.indexOf(form.status) < 0)
            "
            type="text"
            size="mini"
            @click="handleOpenModel('split', scope.row, scope.$index)"
          >编辑</el-button
          >
          <el-button
            :disabled="
              (currentDisabled && title === '查看合同拆分') ||
              (currentDisabled && disabledRules.moreInfo.indexOf(form.status) < 0)
            "
            type="text"
            size="mini"
            @click="handleDelete('contractSplitList', scope.$index)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 8px;margin-bottom: 18px;"  v-if="form.contractSplitTag=='1'">
      合同签约金额：<span style="color: red; margin-right: 2px; font-size: 18px">{{Number(form.contractAmount).toFixed(2)}}</span>元，
      拆分合同金额：<span style="color: red; margin-right: 2px; font-size: 18px">{{ totalSplitAmount(form.contractSplitList) }}</span>元
    </div>


    <div class="title" style="padding-top: 0px">
      合同明细<el-button
        @click="handleOpenModel('moreInfo')"
        :disabled="
          (currentDisabled && title === '查看合同信息') ||
          (currentDisabled && disabledRules.moreInfo.indexOf(form.status) < 0)
        "
        type="warning"
        size="mini"
        >新增</el-button
      >
    </div>
    <el-table :data="form.contractInformationDetailList" style="width: 99%; margin: 0 auto">
      <el-table-column label="序号" type="index" align="center" :index="indexMethod"> </el-table-column>
      <el-table-column algin align="center" label="费用类型名称">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.contract_expense" :value="scope.row.expenseType" />
        </template>
      </el-table-column>
      <el-table-column prop="num" align="center" label="数量"> </el-table-column>
      <el-table-column prop="amount" align="center" label="金额"> </el-table-column>
      <el-table-column align="center" label="操作" width="160px">
        <template slot-scope="scope">
          <el-button
            :disabled="
              (currentDisabled && title === '查看合同信息') ||
              (currentDisabled && disabledRules.moreInfo.indexOf(form.status) < 0)
            "
            type="text"
            size="mini"
            @click="handleOpenModel('moreInfo', scope.row, scope.$index)"
            >编辑</el-button
          >
          <el-button
            :disabled="
              (currentDisabled && title === '查看合同信息') ||
              (currentDisabled && disabledRules.moreInfo.indexOf(form.status) < 0)
            "
            type="text"
            size="mini"
            @click="handleDelete('contractInformationDetailList', scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>



    <div class="title" style="margin-top: 10px">
      {{ contractTypeName }}计划<el-button
        @click="handleOpenModel('plan')"
        :disabled="
          (currentDisabled && title === '查看合同信息') ||
          (currentDisabled && disabledRules.plan.indexOf(form.status) < 0)
        "
        type="warning"
        size="mini"
        >新增</el-button
      >
    </div>
    <el-table :data="form.contractPaymentPlanList" style="width: 99%; margin: 0 auto">
      <el-table-column prop="stageName" align="center" label="阶段名称"> </el-table-column>
      <el-table-column prop="stageName1" align="center" label="项目类型" v-if="form.contractSplitTag=='1'"> </el-table-column>
      <el-table-column prop="paymentCondition" align="center" :label="(contractTypeName === '回款' ? contractTypeName : '支付') + '条件'"> </el-table-column>
      <el-table-column prop="paymentPercentage" align="center" :label="(contractTypeName === '回款' ? contractTypeName : '支付') + '比例'">
        <template slot-scope="scope">
          {{ scope.row.paymentPercentage ? scope.row.paymentPercentage.toFixed(2) : '0' }}%
        </template>
      </el-table-column>
      <el-table-column
        prop="paymentAmount"
        align="center"
        :label="'计划' + (contractTypeName === '回款' ? contractTypeName : '支付') + '金额'"
      >
        <template slot-scope="scope">
          {{ scope.row.paymentAmount.toFixed(2) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="plannedPaymentDate"
        align="center"
        :label="'计划' + (contractTypeName === '回款' ? contractTypeName : '支付') + '时间'"
      >
      </el-table-column>
      <el-table-column v-if="contractTypeName === '回款'" prop="invoicingDate" align="center" label="开票日期"> </el-table-column>
      <el-table-column align="center" :label="(contractTypeName === '回款' ? contractTypeName : '支付') + '状态'">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type[contractTypeName == '回款' ? 'payment_collection_status' : 'plan_status']"
            :value="scope.row.paymentStatus"
          />
        </template>
      </el-table-column>

      <el-table-column
        prop="actualPaymentAmount"
        align="center"
        :label="'实际' + (contractTypeName === '回款' ? contractTypeName : '支付') + '金额'"
      >
        <template slot-scope="scope">
          {{ scope.row.actualPaymentAmount ? scope.row.actualPaymentAmount.toFixed(2) : 0 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="actualPaymentDate"
        align="center"
        :label="'实际' + (contractTypeName === '回款' ? contractTypeName : '支付') + '时间'"
      >
      </el-table-column>
      <el-table-column align="center" label="操作"
        ><template slot-scope="scope">
          <el-button
            :disabled="
              (currentDisabled && title === '查看合同信息') ||
              (currentDisabled && disabledRules.plan.indexOf(form.status) < 0)
            "
            @click="handleOpenModel('plan', scope.row, scope.$index)"
            type="text"
            >编辑</el-button
          >
          <el-button
            :disabled="
              (currentDisabled && title === '查看合同信息') ||
              (currentDisabled && disabledRules.plan.indexOf(form.status) < 0)
            "
            type="text"
            style="margin-left: 0"
            @click="handleDelete('contractPaymentPlanList', scope.$index)"
            >删除</el-button
          >
        </template></el-table-column
      >
    </el-table>
    <div style="margin-top: 8px">
      实际{{ contractTypeName === '回款' ? contractTypeName : '支付' }}金额合计：<span
        style="color: red; margin-right: 2px; font-size: 18px"
        >{{ totalPayment(form.contractPaymentPlanList) }}</span
      >元
    </div>
    <div class="title" style="margin-top: 10px">
      合同推进计划<el-button
        @click="handleOpenModel('recommend')"
        :disabled="
          (currentDisabled && title === '查看合同信息') ||
          (currentDisabled && disabledRules.recommend.indexOf(form.status) < 0)
        "
        type="warning"
        size="mini"
        >新增</el-button
      >
    </div>
    <el-table :data="form.contractAdvancePlanList" style="width: 99%; margin: 0 auto">
      <el-table-column prop="title" align="center" label="计划名称"> </el-table-column>
      <el-table-column prop="content" align="center" label="计划内容"> </el-table-column>
      <el-table-column prop="manager" align="center" label="负责人"> </el-table-column>
      <el-table-column prop="startTime" align="center" label="计划开始时间"> </el-table-column>
      <el-table-column prop="endTime" align="center" label="计划结束时间"> </el-table-column>
      <el-table-column align="center" label="操作" widht="120px"
        ><template slot-scope="scope">
          <el-button
            :disabled="
              (currentDisabled && title === '查看合同信息') ||
              (currentDisabled && disabledRules.recommend.indexOf(form.status) < 0)
            "
            @click="handleOpenModel('recommend', scope.row, scope.$index)"
            type="text"
            >编辑</el-button
          >
          <el-button
            style="margin-left: 0px"
            :disabled="
              (currentDisabled && title === '查看合同信息') ||
              (currentDisabled && disabledRules.recommend.indexOf(form.status) < 0)
            "
            type="text"
            @click="handleDelete('contractAdvancePlanList', scope.$index)"
            >删除</el-button
          >
        </template></el-table-column
      >
    </el-table>
    <div slot="footer" class="dialog-footer" v-if="title !== '查看合同信息'">
      <el-button style="margin-right: 0" v-if="!id" @click="handleDraft">保存草稿</el-button>
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" v-loading="loading" @click="submitForm">确 定</el-button>
    </div>
    <split
      :show="modelName === 'split'"
      :dataSource="modelData"
      @save="saveModelData"
      @cancel="handleOpenModel"
    ></split>
    <more-info
      :show="modelName === 'moreInfo'"
      :dataSource="modelData"
      @save="saveModelData"
      @cancel="handleOpenModel"
    ></more-info>
    <plan
      :show="modelName === 'plan'"
      :contractCategory="form.contractCategory"
      :dataSource="modelData"
      :contractAmount="form.contractAmount"
      :contractSplitTag="form.contractSplitTag"
      @save="saveModelData"
      @cancel="handleOpenModel"
      :label="contractTypeName"
    ></plan>
    <recommend
      :show="modelName === 'recommend'"
      :dataSource="modelData"
      @save="saveModelData"
      @cancel="handleOpenModel"
    ></recommend>
  </el-dialog>
</template>
<script>
import { addInformation, updateInformation, getInformation, getContractNumber } from '@/api/biz/contract'
import * as contractApi from '@/api/biz/contract'
import { listProject } from '@/api/biz/project'
import { listSupplier } from '@/api/biz/supplier'
import { listTemplate } from '@/api/biz/approvalTemplate'
import MoreInfo from './MoreInfo.vue'
import Plan from './Plan.vue'
import Recommend from './Recommend.vue'
import Split from './Split.vue'

import { listCustomer } from '@/api/biz/customer'
import TableSelect from '@/components/TableSelect'
import { getDingTalkListApi } from '@/api/biz/approvalTemplate'
import { recycleBinReview } from '@/api/biz/bin'
export default {
  name: 'ContractDetails',
  components: {
    MoreInfo,
    Plan,
    Recommend,
    TableSelect,
    Split
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String || Number,
      default: '',
    },
    bin: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      open: false,
      title: '',
      // 遮罩层
      loading: false,
      // 表单参数
      form: {
        contractCategory: null,
        contractAmount: 0,
        contractSplitTag:0
      },
      // 表单校验
      rules: {
        contractCategory: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
        contractProgress: [{ required: true, message: '请选择合同进度', trigger: 'change' }],
        contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
        contractNumber: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
        contractManager: [{ required: true, message: '请填写合同负责人', trigger: 'blur' }],
        createTime: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
        updateTime: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }],
        contractResponsibleParty: [{ required: false, message: '请填写合同负责主体', trigger: 'blur' }],
        processCode: [{ required: true, message: '请选择审批模板', trigger: 'blur' }],
      },
      supplierList: [],
      supplierLoading: false,
      projectList: [],
      projectLoading: false,
      templateList: [],
      templateLoading: false,
      currentIndex: -1,
      modelName: '',
      modelData: {},
      customeData: {},
      customeList: [],
      customeLading: false,
      disabledRules: {
        // 审核中1 审核通过2 待提审0  审核不通过3
        contractProgress: [1, 2],
        moreInfo: [1, 2],
        recommend: [1, 2],
        plan: [1, 2],
        split:[1, 2]
      },
      currentDisabled: false,
      columns: [
        { label: '项目名称', prop: 'projectName', isLabel: true },
        { label: '项目编号', prop: 'projectNumber' },
        { label: '项目类型', prop: 'projectType', dictName: 'project_type' },
        { label: '项目级别', prop: 'projectLevel', dictName: 'project_level' },
      ],
      contractNumberLoading: false,
      contractTypeName: '',
      disabledCustomer: false,
      dingTalkList: [],
      dingTalkListLoading: false,
      contractSplit:false
    }
  },
  dicts: [
    'contract_category',
    'contract_progress',
    'contract_expense',
    'plan_status',
    'project_level',
    'project_type',
    'contract_responsible_party',
    'contract_sign',
    'contract_number',
    'payment_collection_status',
    'sys_business_line'
  ],
  watch: {
    show: {
      handler(val) {
        this.open = val
      },
    },
    disabled: {
      handler(val) {
        this.currentDisabled = val
      },
    },
    open: {
      handler(val) {
        this.reset()
        if (val) {
          let contractDetails = localStorage.getItem('ContractDetails')
          if (this.disabled) {
            this.title = '查看合同信息'
          } else {
            this.title = this.id ? '修改合同信息' : '添加合同信息'
          }
          if (this.id) {
            const callback = (response) => {
              console.log(response.data)
              if (response.data.contractSplitTag=='1') {
                this.contractSplit=true;
              }
              if (response.data.projectId) {
                response.data.project = {
                  projectName: response.data.projectName,
                  id: response.data.projectId,
                }
              }

              if (response.data.customerId) {
                this.customeList = [
                  {
                    customerName: response.data.customerName,
                    id: response.data.customerId,
                  },
                ]
              }
              if (response.data.supplierId) {
                this.supplierList = [
                  {
                    supplierName: response.data.supplierName,
                    id: response.data.supplierId,
                  },
                ]
              }
              if (response.data.processCode) {
                this.templateList = [
                  {
                    name: response.data.processTemplateName,
                    processCode: response.data.processCode,
                  },
                ]
              }
              if (response.data.contractManager) {
                this.dingTalkList = [
                  {
                    dingTalkUserName: response.data.contractManager,
                    userId: null,
                  },
                ]
              }
              if (response.data.status === 1 || response.data.status === 2) {
                this.currentDisabled = true
              }

              const [numberType] = this.dict.type.contract_number.filter(
                (item) => response.data.contractNumber.indexOf(item.value) > -1
              )
              if (numberType) {
                response.data.contractNumberType = numberType.value;
              } else if (response.data.remark) {
                response.data.contractNumberType = response.data.remark;
              }else{
                response.data.contractNumberType ='ZDY';
              }

              this.form = response.data
            }
            if (!this.bin) {
              getInformation(this.id).then(callback)
            } else {
              recycleBinReview(this.id).then(callback)
            }
          } else {
            if (contractDetails) {
              const draft = JSON.parse(contractDetails)
              Object.keys(draft).map((key) => {
                this[key] = draft[key]
              })
            }
            if (this.supplierList.length === 0) {
              this.getSupplierList()
            }
            if (this.templateList.length === 0) {
              this.getApprovalTemplateList()
            }
            if (this.customeList.length === 0) {
              this.getCustomer()
            }
            if (this.dingTalkList.length === 0) {
              this.getDingTalkList()
            }
          }
        } else {
          this.supplierList = []
          this.templateList = []
          this.customeList = []
          this.dingTalkList = []
          this.currentDisabled = false
          this.$emit('cancel', false)
        }
      },
    },
    'form.contractCategory'(newVal, oldVal) {
      if (newVal !== oldVal) {
        if (newVal) {
          this.contractTypeName = newVal == 1 ? '回款' : '付款'
        } else {
          this.contractTypeName = ''
        }
      }
    },
  },
  methods: {
    getDingTalkList(query = '') {
      this.dingTalkListLoading = true
      getDingTalkListApi({
        keyword: query,
        pageNum: 1,
        pageSize: 10,
      })
        .then(({ rows = [] }) => {
          this.dingTalkList = rows
          this.dingTalkListLoading = false
        })
        .catch(() => {
          this.dingTalkListLoading = false
        })
    },
    projectSelect(data = {}) {
      const formData = this.form
      formData.project = data
      formData.projectName = data.projectName
      formData.projectId = data.id
      formData.winBiddingDate = data.winBiddingDate
      if (data.customerId && formData.contractCategory == '1') {
        this.customeList = [
          {
            id: data.customerId,
            customerName: data.customerName,
          },
        ]
        if (!formData.contractId) {
          this.disabledCustomer = true
        }
        formData.customerId = data.customerId
      } else {
        formData.customerId = null
        this.customeList = []
        this.disabledCustomer = false
      }
      this.form = { ...formData }
    },
    totalPayment(data = []) {
      const arr = data.map((item) => {
        if (item.actualPaymentAmount && item.actualPaymentAmount > 0) {
          return item.actualPaymentAmount
        }
        return 0
      })
      const text = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
      return text.toFixed(2)
    },
    totalSplitAmount(data = []) {
      const arr = data.map((item) => item.contractAmount)
      const text = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
      return text.toFixed(2)
    },
    handleDraft() {
      const data = { ...this._data }
      const deleteData = ['dict', 'open', 'loading', 'projectLoading', 'supplierLoading', 'templateLoading']
      deleteData.map((keys) => {
        delete data[keys]
      })
      localStorage.setItem('ContractDetails', JSON.stringify(data))
      this.$modal.msgSuccess('保存草稿成功')
    },
    getProjectListPop(data) {
      return listProject(data)
    },
    customerClear() {
      this.form.customerId = null
      this.form.customerName = null
      this.getCustomer('')
    },
    getCustomer(query = '') {
      this.customeLading = true
      listCustomer({ customerName: query, pageNum: 1, pageSize: 10 })
        .then((res) => {
          this.customeList = res.rows
          this.customeLading = false
        })
        .catch((error) => {
          this.customeLading = false
        })
    },
    // 取消按钮
    cancel() {
      this.reset()
      this.open = false
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractCategory: null,
        contractProgress: null,
        contractName: null,
        contractNumber: null,
        contractManager: null,
        supplierId: null,
        projectId: null,
        contractAmount: null,
        contractResponsibleParty: null,
        contractSignDate: null,
        winBiddingDate: null,
        signObject: null,
        customerId: null,
        customerName: null,
        contractSplitList: [],
        contractInformationDetailList: [],
        contractPaymentPlanList: [],
        contractAdvancePlanList: [],
        coverImg: null,
        status: 0,
        project: null,
        annexDtoList: null,
        contractSplitTag: 0,
        remark:null
      }
      this.resetForm('form')
      this.contractSplit=false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleOpenModel(name = '', data = {}, index = -1) {
      this.modelName = name
      this.modelData = data
      this.currentIndex = index
    },
    /** 提交按钮 */
    submitForm() {
      this.loading = true
      this.$refs['form'].validate((valid) => {
        if (valid) {

          this.form.remark=this.form.contractNumberType;
          if (this.form.contractId != null) {
            let current = JSON.parse(JSON.stringify(this.form))
            console.log(current)
            if (this.form.status === 1 || this.form.status === 2) {
              // current = {
              //   contractId: current.contractId,
              //   contractNumber: current.contractNumber,
              //   contractName: current.contractName,
              //   contractCategory: current.contractCategory,
              //   contractInformationDetailList: current.contractInformationDetailList,
              //   contractPaymentPlanList: current.contractPaymentPlanList,
              //   contractAdvancePlanList: current.contractAdvancePlanList,
              //   contractProgress: current.contractProgress,
              // }
              // delete current.coverImg
            }
            updateInformation(current)
              .then((response) => {
                this.loading = false
                this.$modal.msgSuccess('修改成功')
                this.open = false

                this.$emit('refresh', false)
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            addInformation(this.form)
              .then((response) => {
                this.loading = false
                this.$modal.msgSuccess('新增成功')
                this.open = false
                localStorage.removeItem('ContractDetails')
                this.$emit('refresh', false)
              })
              .catch(() => {
                this.loading = false
              })
          }
        } else {
          this.loading = false
        }
      })
    },
    getSupplierList(query = '') {
      this.supplierLoading = false
      listSupplier({
        supplierName: query,
        pageNum: 1,
        pageSize: 10,
      })
        .then((res) => {
          const result = res.rows
          this.supplierList = result

          this.supplierLoading = false
        })
        .catch((err) => {
          this.supplierLoading = false
          this.supplierList = []
        })
    },
    getProjectList(query = '') {
      this.projectLoading = true
      listProject({
        projectName: query,
        pageNum: 1,
        pageSize: 10,
      })
        .then((res) => {
          const result = res.rows
          this.projectList = result
          this.projectLoading = false
        })
        .catch((err) => {
          this.projectLoading = false
          this.projectList = []
        })
    },
    getApprovalTemplateList(query = '') {
      /*this.templateLoading = true
      listTemplate({
        name: query,
        pageNum: 1,
        pageSize: 20,
      })
        .then((res) => {
          const result = res.rows
          this.templateList = result
          this.templateLoading = false
        })
        .catch((err) => {
          this.templateLoading = false
          this.templateList = []
        })*/
    },
    saveModelData({ name, data }) {
      const list = [...this.form[name]]
      if (this.currentIndex > -1) {
        list[this.currentIndex] = data
      } else {
        list.push(data)
      }
      this.form[name] = list
      this.handleOpenModel()
    },
    indexMethod(index) {
      return (index + 1) * 1
    },
    handleDelete(agsName, index) {
      const list = this.form[agsName]
      list.splice(index, 1)
      this.form[agsName] = list
    },
    amountCheck(rule, value, callback) {
      if (value <= 0 && rule.required) {
        callback(new Error('请输入合同金额'))
      } else {
        callback()
      }
    },
    getContractNumber(type) {
      if(type=='ZDY'){
        return;
      }
      this.contractNumberLoading = true
      getContractNumber(type)
        .then((res) => {
          this.form.contractNumber = res.msg
          this.contractNumberLoading = false
        })
        .catch(() => {
          this.contractNumberLoading = false
        })
    },
    checkPermi(per) {
      if (this.id) {
        return !this.$auth.hasPermi(per)
      }
      return this.currentDisabled
    },
    handleContractSplitTag(value){
      let tag=value?'1':'0';
      this.form.contractSplitTag=tag;
    }
  },
}
</script>
<style scoped lang="scss">
.scrollMenuBox {
  width: 100%;
  height: 450px;
}
.title {
  padding: 15px 0;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
